package com.yusvn.scm.goods.fenhuo.service;

import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.yusvn.scm.common.BaseService;
import com.yusvn.scm.common.constant.Const;
import com.yusvn.scm.common.kit.RetKit;


/**
 * 批发分货 - 期货
 * @author liugz
 *
 */
public class ScmFenhuoPifaQihuoService222 extends BaseService {
	
	//表1 导出
	public Page<Record> exportHh(Kv kv) {
		kv.set("cid", getCid()); //账套id
		Page<Record> recPage = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoKhdh", kv).paginate(getPage(kv), getLimit(kv));
		return recPage;
	}
	
	//	表4 导出
	public Page<Record> exportFhjgmx(Kv kv) {
		kv.set("cid", getCid()); //账套id
		Page<Record> recPage = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.exportFhjgmx", kv).paginate(getPage(kv), getLimit(kv));
		return recPage;
	}
	
	// 批发期货分货 - 查询客户订货数据
	public Page<Record> pifaQihuoHh(Kv kv) {
		kv.set("cid", getCid()); //账套id
		kv.set("scm_zc", getConfig("scm_zc")); //总仓
		kv.set("scm_ypc", getConfig("scm_ypc").replace("，", ",").split(",")); //样品仓
		kv.set("scm_mdc", getConfig("scm_mdc").replace("，", ",").split(",")); //门店仓
		//StaticLog.debug("log:kv的信息 {}", kv ); //打印日志信息
		
		// 删除客户订货临时表scm_fenhuo_khdh的数据
		Db.use(Const.SCMDB).delete("delete from scm_fenhuo_khdh where cid=? and userid=? ", getCid(), kv.getStr("userid"));
		// 删除客户订货明细临时表scm_fenhuo_khdhmx的数据
		Db.use(Const.SCMDB).delete("delete from scm_fenhuo_khdhmx where cid=? and userid=? ", getCid(), kv.getStr("userid"));
		
		//删除24小时前的分货数据 
		Db.use(Const.SCMDB).templateByString("delete from scm_fenhuo_fhjgmx where cid=#(cid) and userid=#(userid) and createtime<(sysdate-24/24) ", kv).delete();
		
		// 查询数据新增到客户订货临时表scm_fenhuo_khdh
		Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoKhdhAdd", kv).update();
		
		// 查询结果到页面
		Page<Record> recPage = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoKhdh", kv).paginate(getPage(kv), getLimit(kv));
		
		// 查询数据新增到客户订货明细临时表scm_fenhuo_khdhmx
		List<String> spList = recPage.getList().stream().map(r -> r.getStr("spid")).collect(Collectors.toList());
		if(spList.size()>0) {
			kv.set("spid", spList);
			Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoKhdhmxAdd", kv).update();
		}
		
		return recPage;
	}
	
	
	// 批发期货分货 - 查询客户订货明细（临时表中）
	public Page<Record> pifaQihuoKh(Kv kv) {
		kv.set("cid", getCid()); //账套id
		// 客户订货明细临时表中，查询结果到页面
		Page<Record> recPage = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoKh", kv).paginate(getPage(kv), getLimit(kv));
		return recPage;
	}
	
	
	// 批发期货分货 - 3单款分货结果-展示到界面
	public Page<Record> pifaQihuoJg(Kv kv) {
		kv.set("cid", getCid()); //账套id
		Page<Record> recPage = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJg", kv).paginate(getPage(kv), getLimit(kv));
		return recPage;
	}
		
	// 批发期货分货 - 4结果 按客户汇总
	public Page<Record> pifaQihuoJgKhhz(Kv kv) {
		kv.set("cid", getCid()); //账套id
		
		//删除24小时前的分货数据 
		Db.use(Const.SCMDB).templateByString("delete from scm_fenhuo_fhjgmx where cid=#(cid) and userid=#(userid) and createtime<(sysdate-24/24) ", kv).delete();
		
		Page<Record> recPage = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJgKhhz", kv).paginate(getPage(kv), getLimit(kv));
		return recPage;
	}
	
	// 批发期货分货 - 5结果 某客户分货明细
	public Page<Record> pifaQihuoJgKhmx(Kv kv) {
		kv.set("cid", getCid()); //账套id
		Page<Record> recPage = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJgKhmx", kv).paginate(getPage(kv), getLimit(kv));
		return recPage;
	}
	
	
	//查询表1商品更新行颜色
	public List<Record> pifaQihuoJgGxspys(Kv kv) {
		kv.set("cid", getCid()); //账套id
		//统计当前分货结果（用于更新表1颜色）
		List<Record> recList = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJgGxspys", kv).find();
		return recList;
	}
	
	// 批发期货分货 - 查询条件 - 撤销分货(批量)
	public RetKit pifaQihuoCxczCxfh(Kv kv) {
		kv.set("cid", getCid()); //账套id
		List<Record> spArr = JSON.parseArray(kv.getStr("ks"), Record.class); //(JSONArray) kv.get("spid")	
		//删除分货结果临时表
		Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJsCxfhJg", kv).update();
		
		//统计当前分货结果（用于更新表1颜色）
		List<Record> recList = pifaQihuoJgGxspys(kv);
		
		return RetKit.ok("撤销分货完成"+ spArr.size()).setData(recList);
	}

	// 批发期货分货 - 查询条件 - 一键分货(批量)
	public RetKit pifaQihuoCxczYjfh(Kv kv) {
		kv.set("cid", getCid()); //账套id
		List<Record> spArr = JSON.parseArray(kv.getStr("ks"), Record.class);
		
		//分货计算
		RetKit ret = pifaQihuoPljs(kv);
		if(ret.getCode()!=0) {
			return ret;
		}
		
		//统计当前分货结果（用于更新表1颜色）
		List<Record> recList = pifaQihuoJgGxspys(kv);
		
		return RetKit.ok("一键分货完成 "+spArr.size()).setData(recList);
	}

	// 重算分货 TODO
	public RetKit pifaQihuoCsfh(Kv kv) {
		kv.set("cid", getCid()); //账套id
		kv.set("scm_zc", getConfig("scm_zc")); //总仓
		kv.set("scm_ypc", getConfig("scm_ypc").replace("，", ",").split(",")); //样品仓
		kv.set("scm_mdc", getConfig("scm_mdc").replace("，", ",").split(",")); //门店仓
		//查询所有需要计算的 商品的款色（款、色，并按款、色排序）
		List<Record> spList = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJsSpks", kv).find();
		//查询尺码规则
		List<Record> gzcmRecList = Db.use().find("select * from scm_maduan");
		//查询所有需要计算的 商品尺码的库存(款、色、码、库存数)
		List<Record> kccmListAll = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJsSpkcsl", kv).find();
		//查询所有需要计算的 商品采购入库单尺码个数（款、色、尺码个数）
		List<Record> crcmListAll = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJsCrsl", kv).find();
		//查询所有客户的订单明细（区域、客户、款号、颜色、尺码、订货数，并在区域内按剩余量排序）
		List<Record> ddListAll = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJsDdmx", kv).find();
		
		//循环款色
		spfor:
		for(Record sp : spList) {
			
		}
		
		return RetKit.ok();
	}
	
	// 样品仓调拨清样
	public void pifaQihuoDbqy(Kv kv) {
		String cid = getCid(); //
		kv.set("cid", cid); //账套id
		kv.set("scm_xsd_qybl", getConfig("scm_xsd_qybl")); //系统设置的清样比例
		kv.set("scm_ypc", getConfig("scm_ypc").replace("，", ",").split(",")); //样品仓
		kv.set("scm_mdc", getConfig("scm_mdc").replace("，", ",").split(",")); //门店仓
		
		//统计“清样款”本次已分货的客户分货明细及订货明细（哪些尺码未分？ 按客户、款色排序）
		List<Record> fhmxList = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoDbqyFhmx", kv).find();
		//统计“清样款”门店仓及样品仓的库存明细（按款色、门店排序）
		List<Record> kcList = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoDbqyKcmx", kv).find();
		//用于暂存分货结果
		//List<Kv> fhjgList = new ArrayList<Kv>();
		
		
		//循环客户订单
//		for(Record ddmx : fhmxList) {
		Iterator<Record> ddIterator = fhmxList.iterator();
		while(ddIterator.hasNext()) {
			Record ddmx = ddIterator.next();
			//System.out.println( " ddmx:"+ddmx);
			//循环库存
			//for(Record kc : kcList) {
			Iterator<Record> kcIterator = kcList.iterator(); //总仓库存
			while(kcIterator.hasNext()) {
				Record kc = kcIterator.next();
				if(ddmx.getStr("spid").equals(kc.getStr("spid"))
						&& ddmx.getStr("ysid").equals(kc.getStr("ysid"))
						&& ddmx.getStr("cmid").equals(kc.getStr("cmid")) 
						&& kc.getInt("kcsl")>0 //库存数量大于0
						&& ddmx.getInt("sysl")>0 ) { //订单剩余数量大于0
					
					//新增分货数据到集合
					Kv rec = new Kv();
					rec.set("cid", getCid());
					rec.set("userid", kv.getStr("userid"));
					rec.set("khid", ddmx.getStr("khid")); //客户id
					rec.set("qyid", StrKit.isBlank(ddmx.getStr("qyid")) ? "0" : ddmx.getStr("qyid"));
					rec.set("ckid", ddmx.getStr("ckid")); //客户仓库id
					rec.set("skuid", ddmx.getStr("skuid"));
					rec.set("spid", ddmx.getStr("spid"));
					rec.set("fhckid", kc.getStr("fhckid")); //发货仓库id fhckid
					//分货数量
					if(kc.getInt("kcsl")>=ddmx.getInt("sysl") ) {
						rec.set("bcfhsl", ddmx.getInt("sysl"));
						//更新循环集合中的库存，订货剩余数
						kc.set("kcsl", kc.getInt("kcsl")- ddmx.getInt("sysl"));
						ddmx.set("sysl", 0);
					}else {
						rec.set("bcfhsl", kc.getInt("kcsl"));
						//更新循环集合中的库存，订货剩余数
						kc.set("kcsl", 0);
						ddmx.set("sysl", ddmx.getInt("sysl")- kc.getInt("kcsl"));
					}
					
					//获取销售价
					double fprice = 0;
					fprice = Db.use(Const.SCMDB).templateByString("select getfprice2(#(khid), #(spid), to_char(sysdate,'yyyymmdd'), 1, 1) "
							+ "from defbuyer where id=#(khid)", Kv.create().set("spid", ddmx.getStr("spid")).set("khid", ddmx.getStr("khid")) ).queryDouble();
					rec.set("dprice", 0); //标准价 //dd.getStr("dprice")
					rec.set("fprice", fprice); //销售价 GetFPriceAdj(p_BuyerId, p_StyleId, p_billdate, p_saleType, p_retType)
					rec.set("remark", null); 
					//fhjgList.add(rec); 
					//单个保存分货记录到数据库
					Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJgAdd", rec).update();
					
					//移除已经分完的库存尺码
					if(kc.getInt("kcsl")<=0) {
						kcIterator.remove();
					}
					
				}
				
			}
			//移除已经分完的客户订货明细
			if(ddmx.getInt("sysl")<=0) {
				ddIterator.remove();
			}
		}
		
	}
	
	// 批发期货分货 - 批量计算（总仓）
	public RetKit pifaQihuoPljs(Kv kv) {
		String cid = getCid(); //
		kv.set("cid", cid); //账套id
		kv.set("scm_zc", getConfig("scm_zc")); //总仓
		
		System.out.println(" -- 开始分货 --");
		//查询所有需要计算的 商品的款色（款、色，并按款、色排序）
		List<Record> spList = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJsSpks", kv).find();
		//查询尺码规则
		List<Record> gzcmRecList = Db.use().find("select * from scm_maduan");
		//查询所有需要计算的 商品尺码的库存(款、色、码、库存数)，先取总仓的库存
		List<Record> kccmListAll = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJsSpkcsl", kv).find();
		//查询所有需要计算的 商品采购入库单尺码个数（款、色、尺码个数）
		List<Record> crcmListAll = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJsCrsl", kv).find();
		//查询所有客户的订单明细（区域、客户、款号、颜色、尺码、订货数，并在区域内按剩余量排序）
		List<Record> ddListAll = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJsDdmx", kv).find();
		
		//当前分货的仓库默认总仓
		String fhckid = Db.use(Const.SCMDB).queryStr("select id as ckid from defstore where cid=? and store=? ", cid, getConfig("scm_zc"));
		//System.out.println(" 发货仓库fhckid:"+fhckid);
		
		//循环款色
		spfor:
		for(Record sp : spList) {
			System.out.println(" --款色："+sp);
			//统计当前款色的 商品尺码库存
			List<String> kccmList = kccmListAll.parallelStream()
					.filter(r -> r.getStr("spid").equals(sp.getStr("spid")) && r.getStr("ysid").equals(sp.getStr("ysid")) )
					.map(r -> r.getStr("cmid")).collect(Collectors.toList());
			//统计当前款色的 商品采购入库单尺码个数
			int crcmCnt = 0;
			if(crcmListAll.size()>0) {
				Optional<Record> crcmOpt = crcmListAll.parallelStream()
						.filter(r -> r.getStr("spid").equals(sp.getStr("spid")) && r.getStr("ysid").equals(sp.getStr("ysid")) ).findFirst();
				if(crcmOpt != null && crcmOpt.isPresent()) {
					//System.out.println(" ----crcmRec:"+crcmOpt);
					crcmCnt=crcmOpt.get().getInt("qty");
				}
			}
			
			String ppcmgz = Db.use().queryStr("select config_value1 from scm_config where config_code='scm_ppcmgz' ");
			if(!ppcmgz.equals("0")) {
				//匹配尺码规则，得到能分货的商品，暂不开启 TODO
				if( !pljsMaduan(gzcmRecList, kccmList, crcmCnt) ) {
					continue;
				}
			}
			
			//统计当前款色码库存
			List<Record> kcList = kccmListAll.parallelStream()
					.filter(r -> r.getStr("spid").equals(sp.getStr("spid")) && r.getStr("ysid").equals(sp.getStr("ysid")) )
					.collect(Collectors.toList());
			
			//统计当前款色码最大库存
			int kskc = 0;
			OptionalInt kskcOpt = kcList.parallelStream().mapToInt(r -> r.getInt("kcsl")).max();
			if(kskcOpt != null && kskcOpt.isPresent()) {
				kskc = kskcOpt.getAsInt();
			}
						
			//每一轮分货，实际分给客户的次数（用于后面判断是否需要继续下轮分货）
			int fhcs = 0;
			
			//当前款色客户的订单的查询条件
			Kv ddKv = Kv.create().set(kv).set("spid", sp.getStr("spid")).set("ysid", sp.getStr("ysid"));
			
			for(int i=0; i<=kskc; i++) {
				String fhmx = "第"+(i+1)+"轮分货：";
				
				//用于暂存分货结果
				//List<Kv> fhjgList = new ArrayList<Kv>();
				
				//当前款色客户的订单排行（区域、客户、款号、颜色、尺码、订货数，并在区域内按剩余量排序(订货数-已发-已分)）
				List<Record> ddList = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJgDhpx", ddKv).find();
				//System.out.println(" --ddList:"+ddList);
				
				//循环当前款色客户的订单
				Iterator<Record> ddIterator = ddList.iterator();
				while(ddIterator.hasNext()) {
					Record dd = ddIterator.next();
					
					//统计当前客户款色的订单明细
					List<Record> ddmxList = ddListAll.parallelStream()
							.filter(r -> r.getStr("khid").equals(dd.getStr("khid")) && r.getStr("spid").equals(sp.getStr("spid")) && r.getStr("ysid").equals(sp.getStr("ysid")) )
							.collect(Collectors.toList());
//					//判断订单有几个尺码，当前尺码少于总尺码个数60%，则不分此客户 TODO
//					if(ddmxList.size()<3) {
//						continue;
//					}
					//判断库存有几个尺码，当前尺码少于总尺码个数60%，调用重复方法，将库存分到已分的客户上 TODO
					if(kcList.size()<3) {
						continue;
					}
					
					for(Record ddmx : ddmxList) {
						Iterator<Record> kcIterator = kcList.iterator(); //总仓库存
						while(kcIterator.hasNext()) {
							Record kc = kcIterator.next();
							if(kc.getStr("spid").equals(dd.getStr("spid")) 
									&& kc.getStr("ysid").equals(dd.getStr("ysid")) 
									&& kc.getStr("cmid").equals(ddmx.getStr("cmid")) 
									&& kc.getInt("kcsl") > 0 //判断库存是否大于0
									&& ddmx.getInt("sysl") > 0 //判断订单剩余数量是否大于0
									&& dd.getInt("sysl") > 0 
									) {
								
								//库存-1，订货剩余数-1
								kc.set("kcsl", kc.getInt("kcsl")-1);
								dd.set("sysl", dd.getInt("sysl")-1);
								ddmx.set("sysl", ddmx.getInt("sysl")-1);
								//新增分货数据到集合
								Kv rec = new Kv();
								rec.set("cid", getCid());
								rec.set("userid", kv.getStr("userid"));
								rec.set("khid", dd.getStr("khid")); //客户id
								rec.set("qyid", StrKit.isBlank(dd.getStr("qyid")) ? "0" : dd.getStr("qyid"));
								rec.set("ckid", dd.getStr("ckid")); //客户仓库id
								rec.set("skuid", ddmx.getStr("skuid"));
								rec.set("spid", dd.getStr("spid"));
								rec.set("fhckid", fhckid); //发货仓库id fhckid
								rec.set("bcfhsl", 1);
								//获取销售价
								double fprice = 0;
								fprice = Db.use(Const.SCMDB).templateByString("select getfprice2(#(khid), #(spid), to_char(sysdate,'yyyymmdd'), 1, 1) "
										+ "from defbuyer where id=#(khid)", Kv.create().set("spid", dd.getStr("spid")).set("khid", dd.getStr("khid")) ).queryDouble();
								rec.set("dprice", 0); //标准价 //dd.getStr("dprice")
								rec.set("fprice", fprice); //销售价 GetFPriceAdj(p_BuyerId, p_StyleId, p_billdate, p_saleType, p_retType)
								rec.set("remark", null); 
								//fhjgList.add(rec); 
								//单个保存分货记录到数据库
								Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJgAdd", rec).update();
								
								//fhmx = fhmx + " 客户:"+ dd.getStr("khid") +" 商品:"+ dd.getStr("spid") +" 尺码:"+ ddmx.getStr("cmid") + " 数量:1";
								//System.out.println(fhmx);
								fhcs = fhcs + 1;
								
								//如果当前这一轮分货，没有分掉一件库存，则表示没有订单与库存匹配了，则不进行下轮分货
								if(kc.getStr("spid").equals(dd.getStr("spid")) 
										&& kc.getStr("ysid").equals(dd.getStr("ysid"))
										&& fhcs<=0) {
									break spfor;
								}
								//移除已经分完的库存尺码
								if(kc.getInt("kcsl")<=0) {
									kcIterator.remove();
								}
							}
						}
						//移除已经分完的客户订货明细
						if(dd.getInt("sysl")<=0) {
							//ddIterator.remove();
						}
					}
					
				}
				
			}
			//批量保存分货结果到数据库（按款保存）
			//Db.use(Const.SCMDB).batch("", 500);
		}
		System.out.println(" -- 结束分货 --");
		
		//清样调拨分货
		pifaQihuoDbqy(kv);
		
		return RetKit.ok();
	}
	
	// 匹配尺码规则 - 批量 （库存尺码和设置设置的尺码规则进行匹配）
	public boolean pljsMaduan(List<Record> gzcmRecList, List<String> kccmList, int crcmCnt) {
		//库存尺码数量
		int kccmCnt = kccmList.size();
		if(kccmCnt<=0) {
			return false;
		}
		
		//统计能匹配上的尺码数量的临时变量
		int cnt = 0;
		for(Record gzcmRec : gzcmRecList) {
			//将设置的尺码字符以英文逗号分割成数组
			String[] gzcmArr = gzcmRec.getStr("sizes").replace("，", ",").split(",");
			
			//将库存尺码和设置的尺码进行匹配
			for(String kccm : kccmList) {
				for(String gzcm : gzcmArr) {
					if(gzcm.trim().equals(kccm.trim())) {
						cnt = cnt +1;
					}
				}
			}
			
			//设置的规则尺码和库存尺码匹配且设置的规则数量是0， 或者设置的规则尺码和库存尺码匹配且设置的规则数量等于采购入库的尺码数量，则匹配成功
			if((gzcmRec.getInt("qty")==0 && cnt==gzcmArr.length) 
					|| (gzcmRec.getInt("qty")==crcmCnt && cnt==gzcmArr.length) ) {
				System.out.println(" --尺码匹配"+" cnt:"+cnt+ " gzcmArr:"+gzcmArr.length + " kccmCnt:"+kccmCnt + " gzcmArr:"+JSON.toJSONString(gzcmArr));
				return true;
			}
			cnt = 0;
		}
		
		return false;
	}
	
	// 批发期货分货 - 单款分货结果-表4撤销此客户
	public RetKit pifaQihuoJgCxckh(Kv kv) {
		kv.set("cid", getCid()); //账套id
//		//查询撤销客户已分货的商品 TODO
//		List<Record> spList = Db.use(Const.SCMDB).templateByString("select spid from scm_fenhuo_khdhmx "
//				+ "where cid=#(cid) and userid=#(userid) and (#for(x : khid) khid=#(x) #(for.last ? '' : 'or') #end) group by spid ", kv).find();
//		System.out.println(" spid:"+spList.stream().map(r -> r.getStr("spid")) );
//		
//		kv.set("spid", spList.stream().map(r -> r.getStr("spid")) );
		
		//删除分货结果 明细
		int cnt = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJgCxckhmx", kv).update();
		//删除分货结果 整单
		Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJgCxckh", kv).update();
		if(cnt>=0) {
			//调用重算方法，重新计算撤销客户已分的商品，将其分给其他客户 TODO
			//pifaQihuoPCs(kv);
			
			return RetKit.ok("删除此客户成功 "+cnt);
		}
		try {
			
		} catch (Exception e) {
			System.out.println(e);
			return RetKit.fail("删除此客户失败。"); //e.getMessage()
		}
				
		return RetKit.fail("删除此客户失败");
	}
	
	// 批发期货分货 - 单款分货结果-表3撤销此款
	public RetKit pifaQihuoJgCxck(Kv kv) {
		kv.set("cid", getCid()); //账套id
		try {
			int cnt = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJgCxck", kv).update();
			if(cnt>=0) {
				//调用重算方法，重新计算撤销的商品，将其分给其他客户 TODO
				//pifaQihuoCsfh(kv);
				
				return RetKit.ok("删除此款成功 "+cnt);
			}
		} catch (Exception e) {
			System.out.println(e);
			return RetKit.fail("删除此款失败。"); //e.getMessage()
		}
				
		return RetKit.fail("删除此款失败");
	}
	
	// 批发期货分货 - 单款分货结果-表3修改数据
	public RetKit pifaQihuoJgXgsj(Kv kv) {
		kv.set("cid", getCid()); //账套id
		try {
			//
			kv.set("id", StrKit.getRandomUUID());
			//kv.set("dprice", 0); //标准价
			//kv.set("fprice", 0); //销售价
			//kv.set("qyid", null); //区域ID
			
			//先查询判断是否存在，再修改
			// TODO
			
			int cnt = Db.use(Const.SCMDB).template("scmFenhuoPifaQihuo.pifaQihuoJgXgsj", kv).update();
			if(cnt>=0) {
				//调用重算方法，重新计算撤销的商品，将其分给其他客户 TODO
				//pifaQihuoCsfh(kv);
				
				return RetKit.ok("修改成功 "+cnt);
			}
		} catch (Exception e) {
			System.out.println(e);
			return RetKit.fail("修改失败。"); //e.getMessage()
		}
				
		return RetKit.fail("修改失败");
	}
	
	//  批发期货分货 - 表5获取整单备注
	public RetKit pifaQihuoJgHqbz(Kv kv) {
		kv.set("cid", getCid()); //账套id
		Record zdbz = Db.use(Const.SCMDB).templateByString("select zdbz from scm_fenhuo_fhjg "
				+ "where cid=#(cid) and userid=#(userid) and khid=#(khid) ", kv).findFirst();
		return RetKit.ok("获取成功").setData(zdbz);
	}
	
	//  批发期货分货 - 表5保存整单备注
	public RetKit pifaQihuoJgBcbz(Kv kv) {
		kv.set("cid", getCid()); //账套id
		kv.set("zdbz",kv.getStr("zdbz").replace("'", " "));
		//查询是否存在，存在就修改，不存在就新增
		int cnt = Db.use(Const.SCMDB).templateByString("select count(*) as cnt from scm_fenhuo_fhjg "
				+ "where cid=#(cid) and userid=#(userid) and khid=#(khid) ", kv).queryInt();
		int cnt2 = 0;
		if(cnt>0) {
			cnt2 = Db.use(Const.SCMDB).templateByString("update scm_fenhuo_fhjg set zdbz='#(zdbz)' "
					+ "where cid=#(cid) and userid=#(userid) and khid=#(khid) ", kv).update();
		}else {
			cnt2 = Db.use(Const.SCMDB).templateByString("insert into scm_fenhuo_fhjg(id, cid, userid, khid, zdbz) "
					+ "values(GET_SEQ('scm_fenhuo_fhjg'), #(cid), #(userid), #(khid), '#(zdbz)') ", kv).update();
		}
		
		if(cnt2>0) {
			return RetKit.ok("保存成功");
		}
		return RetKit.fail("保存失败");
	}
	
	// 批发期货分货 - 查询条件 - 生成销售单(批量)
	public RetKit pifaQihuoCxczScxxd(Kv kv) {
		kv.set("cid", getCid()); //账套id
		
		//查询设置的默认生成单据用户ID 815
		String czybh = Db.queryStr("select config_value1 from scm_config where config_code='scm_xsd_yhbh' ");
		//String czyid = Db.use(Const.SCMDB).queryStr("select id from sysuser where cid=#(cid) and username=? ", czybh);
		
		//查询设置的默认发货仓ID 468
		String fhckbh = Db.queryStr("select config_value1 from scm_config where config_code='scm_xsd_fhdc' ");
		//String fhckid = Db.use(Const.SCMDB).queryStr("select * from defstore where cid=#(cid) and store=? ", fhckbh);
		try {
			String cid=getCid();
			String userid=kv.getStr("userid");

			//先删除之前临时表用户勾选的id
			Db.use(Const.SCMDB).update("delete from scm_base_ids where cid=? and userid=? and lx='fh_scdj' ", cid, userid);
			
			//存入用户勾选的id到临时表
			JSONArray idsArr = JSON.parseArray(kv.getStr("khid"));
			Object[][] paras = new Object[idsArr.size()][3];
			for(int i=0;i<idsArr.size();i++) {
				paras[i][0] = idsArr.get(i);
				paras[i][1] = cid;
				paras[i][2] = userid;
			}
			Db.use(Const.SCMDB).batch("insert into scm_base_ids(id, cid, lx, userid) values(?, ?, 'fh_scdj', ?)", paras, 100);
			
			//调用存储过程生成销售单及调拨单（传设置的 账套id\分货用户id\发货仓编号\生成单据用户编号）
			Db.use(Const.SCMDB).update("CALL proc_scm_scxsd(?,?,?,?) ", getCid(), kv.getStr("userid"), fhckbh, czybh);
			
			//删除临时表用户勾选的id
			Db.use(Const.SCMDB).update("delete from scm_base_ids where cid=? and userid=? and lx='fh_scdj' ", cid, userid);
			
		} catch (Exception e) {
			System.out.println(e);
			return RetKit.fail("生成单据失败:"+e.getMessage() );
		}
		return RetKit.ok("生成单据成功");
	}

	
	/**
	    --调用函数更新分销价 GetFPrice、GetFPrice2、
	    update BUSsaledt set fprice=GetFPrice(vr.dest,skuid,vr.billdate,v_distype,0,vr.modifyid) where masterid=p_id;
        
        -- 销售价调整单中的销售折扣saletype、退货折扣rettype，(1期货) 用户id暂时设置为空p_userid
		-- GetFPrice2(p_BuyerId in number, p_StyleId in number, p_billdate in number, p_saleType in number, p_retType in number, p_userid in number default null)
		
		select getfprice2(2282, 123694, 20201208, 1, 1, null) 
		from defbuyer where id=2282;
	 */
	
}
